<template>
  <div class="content-warp">
    <div class="header none-border">
      <div class="title w-full">
        <el-tabs class="w-full" @tab-click="handleClick">
          <el-tab-pane
            :label="tab.label"
            v-for="(tab, index) in tabData"
            :key="index"
          ></el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div class="search mt-5">
      <div class="search-left">
        <el-form
          class="search-container"
          ref="searchFromRef"
          :inline="true"
          :model="queryParams"
          @keyup.enter="handleSerch"
        >
          <el-form-item label="项目类型" prop="projectDictId">
            <el-select v-model="queryParams.projectDictId" clearable placeholder="请选择项目类型">
              <el-option
                v-for="item in DC_PMS_PROJECT_TYPE"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="阶段" prop="phaseDictId">
            <el-select v-model="queryParams.phaseDictId" clearable placeholder="请选择阶段">
              <el-option
                v-for="item in DC_PMS_PROJECT_PHASE"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="行业类别" prop="industryDictId">
            <el-select v-model="queryParams.industryDictId" clearable placeholder="请选择行业类别">
              <el-option
                v-for="item in DC_CRM_SECTOR"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="项目周期" prop="projectStartDate">
            <dc-date-range
              v-model:startDate="queryParams.projectStartDate"
              v-model:endDate="queryParams.projectFinishDate"
              valueFormat="YYYY-MM-DD HH:mm:ss"
              :clearable="true"
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="search-right">
        <el-form-item>
          <el-button type="primary" @click="handleSerch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </div>
    </div>
    <div class="operate-container">
      <el-button type="primary" icon="Plus" @click="handleCreateProject">项目立项</el-button>
    </div>
    <el-row class="card-container" :gutter="24" @scroll="pageScroll" v-loading="loading">
      <el-col
        class="card-item"
        :xs="24"
        :sm="12"
        :md="12"
        :lg="8"
        :xl="6"
        v-for="(item, index) in dataList"
        :key="index"
        @click="goDetail(item)"
      >
        <div
          class="card-item_head"
          :style="{
            backgroundColor:
              DC_PMS_PROJECT_PHASE.find(dict => dict?.id === item?.phaseDictId)?.remark || '#000',
          }"
        >
          <div class="head-tag">
            <dc-dict
              type="text"
              :options="DC_PMS_PROJECT_PHASE"
              :value="item.phaseDictId"
              v-if="item.projectCreateStatusId === '1868943255362002945' && item.dictType === 'id'"
            />
            <dc-dict-key
              type="text"
              :options="DC_PMS_PROJECT_PHASE"
              :value="item.phaseDictId"
              v-else-if="
                item.projectCreateStatusId === '1868943255362002945' && item.dictType === 'code'
              "
            />
            <div v-else style="color: #ccc">
              <dc-dict
                type="text"
                :options="DC_PMS_PROJECT_CREATE_STATUS"
                :value="item.projectCreateStatusId"
                v-if="item.dictType2 === 'id'"
              />
              <dc-dict-key
                type="text"
                :options="DC_PMS_PROJECT_CREATE_STATUS"
                :value="item.projectCreateStatusId"
                v-if="item.dictType2 === 'code'"
              />
            </div>
          </div>
          <div class="project-name">{{ item.projectName }}</div>
          <div class="project-code">（{{ item.projectCode }}）</div>
          <div class="star-wrap" @click.stop="doMark(item)">
            <el-button :type="item.remarkColor" icon="Star" circle />
          </div>
          <div
            class="star-wrap ml-5"
            @click.stop="handleDelete(item)"
            v-if="queryParams.levelClass == '草稿中'"
          >
            <el-button icon="Delete" circle />
          </div>
        </div>
        <div class="card-item_content">
          <div class="params-group w-1/2">
            <div class="param-label">项目类型：</div>
            <div class="param-value ellipsis">
              <dc-dict type="text" :options="DC_PMS_PROJECT_TYPE" :value="item.projectDictId" />
            </div>
          </div>
          <div class="params-group w-1/2">
            <div class="param-label">行业类型：</div>
            <div class="param-value ellipsis">
              <dc-dict type="text" :options="DC_CRM_SECTOR" :value="item.industryDictId" />
            </div>
          </div>
          <div class="params-group w-full">
            <div class="param-label">项目周期：</div>
            <div class="param-value ellipsis">
              {{ item.projectStartDate }}-{{ item.projectFinishDate }}
            </div>
          </div>
          <div class="params-group w-full">
            <div class="param-label">负责人：</div>
            <div class="param-value ellipsis">
              <dc-view v-model="item.createUserId" objectName="user" showKey="realName" />
            </div>
          </div>
          <div class="params-group w-full mt-5">
            <div class="param-label">项目进度</div>
            <div class="param-value ellipsis">{{ item.projectProgress || 0 }}%</div>
          </div>
          <div class="params-group w-full">
            <el-progress
              class="w-full"
              :percentage="item.projectProgress"
              :show-text="false"
              :color="
                DC_PMS_PROJECT_PHASE.find(dict => dict?.id === item?.phaseDictId)?.remark || '#000'
              "
            />
          </div>
          <div class="statistics-group w-full">
            <div class="statistics-item">
              <div class="statistics-item_label">计划总数</div>
              <div class="statistics-item_value value_1">{{ item.planTotalNum || 0 }}</div>
            </div>
            <div class="statistics-item">
              <div class="statistics-item_label">已完成</div>
              <div class="statistics-item_value value_2">
                {{ item.planCompletionsNum || 0 }}
              </div>
            </div>
            <div class="statistics-item">
              <div class="statistics-item_label">未完成</div>
              <div class="statistics-item_value value_3">{{ item.planIncompleteNum || 0 }}</div>
            </div>
            <div class="statistics-item">
              <div class="statistics-item_label">已逾期</div>
              <div class="statistics-item_value value_4">{{ item.planOverdueNum || 0 }}</div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script setup name="Projects">
import { reactive, toRefs, onMounted } from 'vue';
import Api from '@/api/index';
import dayjs from 'dayjs';

const { proxy } = getCurrentInstance();

const route = useRoute();
const router = useRouter();

const { DC_CRM_SECTOR, DC_PMS_PROJECT_TYPE, DC_PMS_PROJECT_PHASE, DC_PMS_PROJECT_CREATE_STATUS } =
  proxy.useCache([
    { key: 'DC_CRM_SECTOR' },
    { key: 'DC_PMS_PROJECT_TYPE' },
    { key: 'DC_PMS_PROJECT_PHASE' },
    { key: 'DC_PMS_PROJECT_CREATE_STATUS' },
  ]);

const data = reactive({
  loading: true,
  pageId: '',
  queryParams: {
    current: 1,
    size: 12,
  },
  total: 0,
  tabData: [
    { label: '全部项目', value: '1' },
    { label: '我的创建', value: '2' },
    { label: '我参与的', value: '3' },
    { label: '个人项目集', value: '4' },
    { label: '草稿中', value: '5' },
  ],
  dataList: [],
  collectViewList: [],
});

const { loading, pageId, queryParams, total, tabData, dataList, collectViewList } = toRefs(data);

onMounted(() => {
  pageId.value = route.params.id;
  if (pageId.value !== 'create') getData();
});
// 获取列表数据
const getData = async () => {
  loading.value = true;
  try {
    const params = {
      ...queryParams.value,
      projectFinishDate: queryParams.value.projectFinishDate
        ? dayjs(queryParams.value.projectFinishDate).format('YYYY-MM-DD 23:59:59')
        : '',
    };
    const res = await Api.pdp.project.list(params);
    const { code, data } = res.data;
    if (code === 200) {
      dataList.value = Array.isArray(data.records)
        ? data.records.map(item => {
            try {
              if (isNumericString(item.phaseDictId)) {
                item.dictType = 'id';
              } else {
                item.dictType = 'code';
              }
            } catch (err) {}
            try {
              if (isNumericString(item.projectCreateStatusId)) {
                item.dictType2 = 'id';
              } else {
                item.dictType2 = 'code';
              }
            } catch (err) {}
            return item;
          })
        : [];
      total.value = data.total;
      await collectViewData();
    }
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
};

function isNumericString(str) {
  // 使用正则表达式检测字符串是否为数字字符串
  const regex = /^\d+$/;
  return regex.test(str);
}

// 滚动方法
const pageScroll = e => {
  // 滚动条滚动时，距离顶部的距离
  const scrollTop = e.target.scrollTop;
  // 可视区的高度
  const windowHeight = e.target.clientHeight;
  // 滚动条的总高度
  const scrollHeight = e.target.scrollHeight;
  // 当滚动条滚动到底部 并且 当前数据小于总数时进行翻页
  if (scrollTop + windowHeight === scrollHeight && dataList.value.length < total.value) {
    queryParams.value.current++;
    // 获取下一页的数据
    getData();
  }
};

// 点击搜索
const handleSerch = () => {
  queryParams.value.current = 1;
  getData();
};

//点击重置
const handleReset = () => {
  queryParams.value = {
    current: 1,
    size: 12,
  };
  queryParams.value.current = 1;
  proxy.resetForm('searchFromRef');
  getData();
};

// tab点击
const handleClick = tab => {
  if (tab === '4') {
    queryParams.value = {
      ...queryParams.value,
      current: 1,
      levelClass: tab.props.label,
    };
    getData();
  } else {
    queryParams.value = {
      ...queryParams.value,
      current: 1,
      levelClass: tab.props.label,
    };
    getData();
  }
};

// 处理项目立项
const handleCreateProject = () => {
  router.push({
    path: `/pdp/project/submit/create`,
  });
};

// 查找收藏
const collectViewData = async () => {
  const res = await Api.system.remark.collectView('PROJECT');
  const { code, data } = res.data;
  if (code === 200) {
    collectViewList.value = data;
    // 合并项目数据，初始化项目的remarkColor
    dataList.value.forEach(item => {
      remarkStatus(item);
    });
  }
};

const doMark = project => {
  const compareValue = project.id + ',';
  const collect = collectViewList.value;
  const targetIds = collect ? (collect.targetIds === null ? '' : collect.targetIds) : '';
  if (collect && collect.targetIds && collect.targetIds.includes(compareValue)) {
    // 已收藏
    // 取消收藏
    collect.targetIds = targetIds.replace(compareValue, '');
  } else {
    // 未收藏
    // 收藏
    collect.targetIds = targetIds + compareValue;
  }
  collection(collect, project, compareValue);
};

const remarkStatus = project => {
  const compareValue = project.id + ',';
  project.remarkColor = changeRemarkColor(compareValue);
};

const changeRemarkColor = compareValue => {
  if (
    collectViewList.value &&
    collectViewList.value.targetIds &&
    collectViewList.value.targetIds.includes(compareValue)
  ) {
    return 'warning';
  } else {
    return 'default';
  }
};

// 前往详情
const goDetail = project => {
  // 草稿
  if (
    project.projectCreateStatusId === '1868943322877714433' ||
    project.projectCreateStatusId === '1868943423935275009'
  ) {
    router.push({
      path: `/pdp/project/submit/${project.id}`,
    });
  } else {
    router.push({
      path: `/pdp/project/detail/overview/${project.id}`,
    });
  }
};

// 收藏
const collection = async (collect, project, compareValue) => {
  const res = await Api.system.remark.collectRemark('PROJECT', collect);
  const { code, msg } = res.data;
  if (code === 200) {
    await getData();
    proxy.$message.success(msg);
    collectViewList.value = collect;
    project.remarkColor = changeRemarkColor(compareValue);
  }
};

// 删除
const handleDelete = async item => {
  const ids = item.id;
  proxy
    .$confirm(`确定将“[${ids}]”数据删除?`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => Api.pdp.project.delete({ ids }))
    .then(() => {
      proxy.$message({
        type: 'success',
        message: '操作成功!',
      });
      getData();
    });
};
</script>
<style lang="scss" scoped>
.card-container {
  margin: 0 -8px !important;
  overflow: auto;

  .card-item {
    padding: 0 8px !important;
    margin-bottom: 16px !important;
    display: flex;
    flex-direction: column;
    border-radius: 8px;
    overflow: hidden;
    height: 266px;

    &_head {
      position: relative;
      padding: 0 16px;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      height: 48px;
      background-color: #1d65f3;
      border-radius: 8px;
      z-index: 10;
      font-size: 15px;
      color: #fff;

      .head-tag {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 37px;
        height: 24px;
        background: #fff;
        border-radius: 4px;
        font-weight: bold;
        font-size: 12px;
        color: #1d65f3;
        line-height: 12px;
        text-align: center;
        cursor: pointer;
        user-select: none;
      }

      .project-name {
        margin: 0 4px 0 8px;
        font-weight: bold;
      }

      .project-code {
        flex: 1;
        font-weight: 400;
      }

      // .star-wrap {
      //   position: absolute;
      //   z-index: 7;
      //   width: 32px;
      //   height: 32px;
      //   right: 6px;
      //   top: 8px;
      //   //background-color: rgba(255,255, 225, 0.2);
      // }
    }

    &_content {
      display: flex;
      flex-wrap: wrap;
      box-sizing: border-box;
      margin-top: -8px;
      flex: 1;
      background-color: #f6f8fa;
      border: 1px solid #dadbe0;
      border-top: none;
      border-radius: 0 0 8px 8px;
      padding: 32px 16px 16px 16px;
      font-size: 14px;
      line-height: 14px;
      font-weight: 400;

      .params-group {
        display: flex;

        .param-label {
          width: 70px;
          color: #666;
        }

        .param-value {
          flex: 1;
          color: #333;
        }
      }

      .statistics-group {
        display: flex;

        .statistics-item {
          display: flex;
          flex-direction: column;
          flex: 1;
          text-align: center;

          &_label {
            margin-top: 5px;
            color: #666;
          }

          &_value {
            margin-top: 8px;
            font-weight: bold;

            &.value {
              &_1 {
                color: #333;
              }

              &_2 {
                color: #23c69f;
              }

              &_3 {
                color: #f78431;
              }

              &_4 {
                color: #e12137;
              }
            }
          }
        }
      }
    }
  }
}
</style>
